<template>
  <div>
    <!-- 自定义导航 -->
    <van-nav-bar :title="navName" left-text="取消" right-text="保存" left-arrow @click-left="cancel" @click-right="save" :fixed="true"/>
    <van-cell-group style="padding-top:51px">
      <van-field v-model="from.name" label="空间名称" placeholder="请输入" required clearable :error="checkVal.nameErr" @focus="checkVal.nameErr=false" input-align="right"/>
      <van-field type="number" v-model="from.area" label="面积" placeholder="请输入" clearable :error="checkVal.areaErr" @focus="checkVal.areaErr=false" input-align="right"/>
      <van-field type="number" v-model="from.height" label="高度" placeholder="请输入" clearable input-align="right"/>
      <van-cell title="请选择空间类别" is-link :value="from.spaceClass" @click="spaceClass=true" required/>
      <!-- 空间类别 弹层 -->
      <van-action-sheet v-model="spaceClass" :actions="spaceActions" @select="spaceSelect"/>

      <van-cell-group>
        <van-switch-cell v-model="from.isInner" :class="openstyles3" title="是否室内空间" @change="changecolor3" active-value="1" inactive-value="0" active-color="#13ce66"/>
      </van-cell-group>

      <van-cell title="请选择地面类型" is-link :value="from.groundName" @click="groundClass=true" required/>
      <!-- 地面类型 弹层 -->
      <van-action-sheet v-model="groundClass" :actions="groundActions" @select="groundSelect"/>

      <van-cell title="请选择材质类型" is-link :value="from.qualityName" @click="qualityClass=true" required/>
      <!-- 材质类型 弹层 -->
      <van-action-sheet v-model="qualityClass" :actions="qualityActions" @select="qualitySelect"/>

      <!-- <van-field type="number" label="器具列表数量" label-width="150px" input-align="right" clearable v-model="from.wareNum" placeholder="请输入" required :error="checkVal.wareNumErr" @focus="checkVal.wareNumErr=false"/> -->
      <van-cell-group>
        <van-switch-cell v-model="from.isMaintained" :class="openstyles2" title="是否需要维护"  @change="changecolor2" active-value="1" inactive-value="0" active-color="#13ce66"/>
        <van-switch-cell v-model="from.status" :class="openstyles" title="是否启用该空间"  @change="changecolor" active-value="1" inactive-value="2" :disabled="isStatus" active-color="#13ce66"/>
      </van-cell-group>
      <van-field type="textarea" label="描述" v-model="from.description" placeholder="请输入" clearable :maxlength="140" show-word-limit autosize/>
    </van-cell-group>
  </div>
</template>
<script>
  export default {
  data(){
    return{
      isStatus: false, //是否启用 
      //错误检查
      checkVal:{
        nameErr: false,
        areaErr: false,
        wareNumErr: false,
      },  
      spaceClass:false,//空间类别弹层
      groundClass:false, //地类型弹层
      qualityClass:false, //材质弹层
      navName: localStorage.getItem('navName'), //导航名称
      floorClass: false,  //空间类别 弹层变量
      spaceActions: [
        // {id: 1, classfication: "floorClass", subname: "装修的"},
      ],
      groundActions:[
        // {id: 1, classfication: "floorClass", subname: "木板"},
      ],
      qualityActions:[],
      openstyles:'', 
      openstyles2:'', 
      openstyles3:'',
      
      from:{
        name:'',          //空间名称
        area: '',          //总面积
        height: '',        //高度
        spaceClassId:'',  //空间类别ID
        spaceClass:'',    //空间类别名
        isInner: '1',    //室内空间
        groundId:'',      //地面类型ID
        groundName:'',    //地面类型名
          qualityName:'',   //材质类型名
          qualityId:'',    //材质类ID
        //wareNum: '',     //器具列表数量
        isMaintained:'1',  //是否需要维护
        status: '1',        //1-启用 2-停用
        description:'',     //描述
      },
    }
  },
  methods:{
    //选择空间类别
    spaceSelect(item) {
      // 点击选项时默认不会关闭菜单，可以手动关闭
      this.spaceClass = false;
      this.from.spaceClass = item.subname;  //选中的空间类别名（赋值）
      this.from.spaceClassId = item.id;
    },
    //地面类型类别
    groundSelect(item) {
      this.from.qualityName = "";  //清空原先材质数据
      this.from.qualityId = "";    //清空原先材ID质数据
      // 点击选项时默认不会关闭菜单，可以手动关闭
      this.groundClass = false;
      this.from.groundName = item.subname;  //选中的地面类别名（赋值）
      this.from.groundId = item.id;
      this.qualityClsaa(item.subname);
    },
    //材质类型 （是地面类型的二级数据）
    qualitySelect(item) {
      // 点击选项时默认不会关闭菜单，可以手动关闭
      this.qualityClass = false;
      this.from.qualityName = item.subname;  //选中的地面类别名（赋值）
      this.from.qualityId = item.id;
    },
     //空间类别数据获取
    spacesClsaa(){
      this.$http({
        url: '/api/SoftSpaceXamine/getSpaceXamineList',
        method: 'get',
        headers: {
          'Authorization': localStorage.getItem('token'),
        },
        params:{
          limit: 99,
          page: 0,
        }
      }).then(res =>{
        if(res.data.errcode == 0){
          if(res.data.data.list.length == 0 ){
            this.spaceClass = false;
            this.$toast.fail("空间类别为空");
            return;
          }
           for (let index = 0; index < res.data.data.list.length; index++) {
            this.spaceActions.push(
              {
                id: res.data.data.list[index].id,
                subname: res.data.data.list[index].examineClass,
            });
           }
        }
      })
    },
    //地面类别数据获取
    getgroundClsaa(){
      this.$http.get(`/api/constants/getConstantsList?classfication=ground&status=1`,{
        headers: {
          'Authorization': localStorage.getItem('token'),
        }
      }).then(res =>{
        if(res.data.errcode == 0){
          if(res.data.data.length == 0 ){
            this.groundClass = false;
            this.$toast.fail("地面类别为空");
            return;
          }
           for (let index = 0; index < res.data.data.length; index++) {
            this.groundActions.push(
              {
                id: res.data.data[index].id,
                subname: res.data.data[index].name,
                classfication: res.data.data[index].classfication 
            });
           }
        }
      })
    },
    //材质类别数据获取(接口要改)
    qualityClsaa(val){
      this.$http.get('/api/constants/getConstantsList?classfication=texture&status=1', {
        headers:{ 'Authorization':localStorage.getItem('token'),}
      }).then(res =>{
        if(res.data.errcode == 0){
          if(res.data.data.length == 0){
            this.qualityClass = false;
            this.$toast.fail("材质类别为空");
          }
          this.qualityActions = [];
          for (let index = 0; index < res.data.data.length; index++) {
            this.qualityActions.push(
              {
                id: res.data.data[index].id,
                subname: res.data.data[index].name,
                classfication: res.data.data[index].classfication 
            });
           }
        }
      })
    },
    //取消按钮
    cancel() {
     this.$dialog.confirm({
      title: '提示', message: '是否放弃本次编辑？'
      }).then(() => {
        this.$router.go(-1);//返回上一层
      }).catch(() => {});
    },
    //修改按钮
    save() {
      if(!this.from.name){
        this.checkVal.nameErr = true;
        return this.$toast("空间名称不能为空！");
      }
      // if(!this.from.area){
      //   this.checkVal.areaErr = true;
      //   return this.$toast("面积不能为空！");
      // }
      
      // if(!this.from.wareNum){
      //   this.checkVal.wareNumErr = true;
      //   return this.$toast("数量不能为空！");
      // }
      let spacesID = sessionStorage.getItem("spacesID");
       this.from.qualityName 
      this.from.qualityId 
      let data = {
        id: spacesID,
        name: this.from.name,
        area: parseFloat(this.from.area),
        height: parseFloat(this.from.height),
        spaceClassId:this.from.spaceClassId,
        isInner: parseInt(this.from.isInner),
        groundId: this.from.groundId,
        qualityId: this.from.qualityId,
        // wareNum: parseInt(this.from.wareNum),
        isMaintained:parseInt(this.from.isMaintained),
        status: parseInt(this.from.status),
        description: this.from.description,
      }
      
      this.$http.put(`/api/spaces/updateSpaces`, data,{
        headers: {
          'Authorization': localStorage.getItem('token'),
        }
      }).then(res =>{
        if(res.data.errcode == -3){
          this.nameErr = true;
          this.$toast.fail("编辑失败，楼层名重复");
          return;
        }
        if(res.data.errcode == 0){
          this.from = {};
          this.$toast('空间编辑成功!');
          this.$router.replace({path: '/spaces'})
        }
      })
    },
    // 开关改变颜色
    changecolor(){
      if(this.from.isMaintained == 1){
        this.openstyles='open';
      }else{
        this.openstyles='';
      }
    },
    changecolor2(){
      if(this.from.isMaintained == 1){
        this.openstyles2='open';
      }else{
        this.openstyles='';
      }
    },changecolor3(){
      if(this.from.isMaintained == 1){
        this.openstyles3='open';
      }else{
        this.openstyles='';
      }
    },
    //判断父级空间是否启用 父级未启用 子级不可启用
    getIsStatus(){
      let floorID = sessionStorage.getItem('floorID');
      this.$http({
        url: "/api/floors/getFloorsById",
        method: "get",
        params: {
          id: floorID,
        },
        headers:{
          'Authorization': localStorage.getItem('token'),
        }
      }).then(res =>{
        console.log(res);
        if(res.data.errcode == 0){
          if(res.data.data.status==2){
            this.isStatus = true;
            this.from.status = 2;
          }
        }
      }).catch(err =>{
        console.log({err});
      })
    }
  },
  created(){
    this.getIsStatus();
    this.spacesClsaa();
    this.getgroundClsaa();
    let val = JSON.parse(sessionStorage.getItem('spacesVal'));
    this.qualityClsaa(val.ground); //取到地面类型的值
    this.from={
      id: val.id,  //空间ID
      name: val.name,  //空间名称
      area: val.area, //面积
      height: val.height,  //高度
      spaceClassId: val.spaceClassId, //空间类别ID
      spaceClass: val.spaceClass, //空间类别
      isInner: (val.isInner).toString(),  //是否是室内空间
      groundId: val.groundId, //地面类型ID
      groundName: val.groundName, //地面类型名
        qualityName: val.qualityName,  //材质类型名
        qualityId: val.qualityId,  //材质类ID
      //wareNum: val.wareNum,  //器具数量
      isMaintained: (val.isMaintained).toString(), //是否需要服务
      status: (val.status).toString(),  //1-启用 2-停用
      description:val.description,    //描述description
    }
    
  }
}
</script>
<style scoped>
  .van-cell {
    color: #979797 !important;
  }
  /* 开关选择颜色 */
  .open{
    color: #333 !important;
  }
</style>